package com.lagou.boot;

import com.lagou.annotation.Service;
import com.lagou.annotation.SpringBootApplication;
import com.lagou.handle.HelloServiceHandle;
import com.lagou.util.JSONSerializer;
import com.lagou.util.RpcDecoding;
import com.lagou.util.RpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServerBoot {

    private static List<String> classNames = new ArrayList<>(); //类的权限定类名
    private static Map<String,Object> ioc = new HashMap<>(); //ioc容器

    public static void run(Class<?> clazz, Object[] args)  {
        try {
            //获取注解
            if(clazz.isAnnotationPresent(SpringBootApplication.class)){
                    //扫描该启动类下的所有包下的类
                    scanPackage(clazz.getPackageName());
                    //创建service bean实例,并放入ioc容器中
                    initBean();
            }
            startServer("127.0.0.1",8888);
            System.out.println("服务端已启动。。。。");
        } catch (InterruptedException | ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }

    private static void initBean() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        if (classNames.size() == 0)return;
        for (int i = 0; i < classNames.size(); i++) {
            String className = classNames.get(i);
            Class<?> aClass = Class.forName(className);
            if(aClass.isAnnotationPresent(Service.class)){
                Service annotation = aClass.getAnnotation(Service.class);
                if (annotation.value() != ""){
                    ioc.put(annotation.value(),aClass.newInstance());
                }else{
                    ioc.put(aClass.getSimpleName(),aClass.newInstance());
                }
            }
        }
    }

    private static void scanPackage(String basePackage) {
        //com.lagou ==> 转换成磁盘的文件目录
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + basePackage.replaceAll("\\.", "/");
        //递归获取className
        File root = new File(path);
        File[] files = root.listFiles();
        for (File file : files) {
            if(file.isDirectory()){
                //如果是目录，则递归下层
                scanPackage(basePackage+"."+file.getName());
            }else if (file.getName().endsWith(".class")){
                String className = basePackage + "." + file.getName().replaceAll(".class", "");
                //添加权限定类名到集合当中
                classNames.add(className);
            }
        }
    }

    public static void startServer(String host,int port) throws InterruptedException {
        //创建线程池
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //创建启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //配置引导类
        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new RpcDecoding(RpcRequest.class,new JSONSerializer()))
                                .addLast(new StringEncoder())
                                .addLast(new HelloServiceHandle(ioc));
                    }
                });
        //绑定端口
        serverBootstrap.bind(host,port).sync();
    }
}
